package ext.tianma.part.finishedProduct.util;

import java.util.ArrayList;
import java.util.Collection;

import wt.util.WTException;
import wt.util.range.Range;

import com.ptc.core.lwc.common.view.AttributeDefinitionReadView;
import com.ptc.core.lwc.common.view.ConstraintDefinitionReadView;
import com.ptc.core.lwc.common.view.EnumerationEntryReadView;
import com.ptc.core.lwc.common.view.PropertyValueReadView;
import com.ptc.core.lwc.common.view.ScreenDefinitionReadView;
import com.ptc.core.lwc.common.view.TypeDefinitionReadView;
import com.ptc.core.lwc.server.LWCFilterBasedConstraint;
import com.ptc.core.lwc.server.TypeDefinitionServiceHelper;
import com.ptc.core.meta.common.DiscreteSet;
import com.ptc.core.meta.common.OperationIdentifier;

import ext.tianma.part.finishedProduct.vo.AttrRuleVo;




public class TypesUtil {
	private static final String PROP_displayName = "displayName";
	public static final String ATYPE_basic = "basic";
	public static final String ATYPE_model = "model";
	public static final String ATYPE_mapping = "mapping";
	public static final String ATYPE_iba = "iba";
	public static final String ATYPE_ref = "ref";

	/**
	 * 获取属性的合法值列表
	 * @param typeName
	 * @param attrName
	 * @return
	 * @throws WTException
	 */
	public static ArrayList<String> getlegalValueList(String typeName,
			String attrName) throws WTException {
		TypeDefinitionReadView tv = TypeDefinitionServiceHelper.service.getTypeDefView(typeName);
		AttributeDefinitionReadView av = tv.getAttributeByName(attrName);// 得到属性视图
		PropertyValueReadView propertyValueView = av.getPropertyValueByName(PROP_displayName);
		String displayName = String.valueOf(propertyValueView.getValue());
		AttrRuleVo avo = new AttrRuleVo();
		avo.setDataType(av.getDatatype().getName());
		avo.setDisplayName(displayName);

		ArrayList<String> retList = new ArrayList<String>();
		for (ConstraintDefinitionReadView cons : av.getAllConstraints()) {
			if ("com.ptc.core.meta.container.common.impl.DiscreteSetConstraint"
					.equals(cons.getRule().getRuleClassname())) {// 合法值
				if (cons.getRuleDataObj() != null
						&& cons.getRuleDataObj().getRuleData() instanceof DiscreteSet) {
					DiscreteSet dataSet = (DiscreteSet) cons.getRuleDataObj()
							.getRuleData();
					Object[] els = dataSet.getElements();
					for (Object el : els) {
						retList.add(String.valueOf(el));
					}
				}
			}
		}

		return retList;
	}
	
	/**
	 * @param typeName 类型名称，如：wt.part.WTPart
	 * @param attrName 属性名称，如：name
	 * @return
	 * @throws WTException
	 */
	public static AttrRuleVo queryTypeDef(String typeName, String attrName) throws WTException {
		TypeDefinitionReadView tv = TypeDefinitionServiceHelper.service.getTypeDefView(typeName);
		AttributeDefinitionReadView av = tv.getAttributeByName(attrName);//得到属性视图
		PropertyValueReadView propertyValueView = av.getPropertyValueByName(PROP_displayName);
		String displayName = String.valueOf(propertyValueView.getValue());
		AttrRuleVo avo = new AttrRuleVo();
		avo.setDataType(av.getDatatype().getName());
		avo.setDisplayName(displayName);
		analyzeConstraint(av, avo);
		
		return avo;
	}
	
	private static void analyzeConstraint(AttributeDefinitionReadView av, AttrRuleVo avo) {
		for (ConstraintDefinitionReadView cons : av.getAllConstraints()) {
			
			if("com.ptc.core.meta.container.common.impl.StringByteLengthConstraint".equals(cons.getRule().getRuleClassname())) {//【建议值】时，研究中
				System.out.println("建议值1");
			}
			
			else if("com.ptc.core.meta.container.common.impl.SuggestedValuesConstraint".equals(cons.getRule().getRuleClassname())) {//建议值
				if (cons.getRuleDataObj() != null && cons.getRuleDataObj().getRuleData() instanceof DiscreteSet) {
					DiscreteSet dataSet = (DiscreteSet) cons.getRuleDataObj().getRuleData();
					Object[] els = dataSet.getElements();
					for (Object el : els) {
						avo.getSuggestedValuesList().add(String.valueOf(el));
					}
				}else if(cons.getRule().getKey()!=null && 
						cons.getRule().getKey().contains("com.ptc.core.lwc.server.LWCEnumerationBasedConstraint") && 
						cons.getRuleDataObj()!=null){
					Collection<EnumerationEntryReadView> coll=cons.getRuleDataObj().getEnumDef().getAllEnumerationEntries().values();
					for(EnumerationEntryReadView eerv:coll){
						avo.getEnumMap().put(eerv.getName(),eerv.getPropertyValueByName(PROP_displayName).getValueAsString());
					}
				}
			}
			
			else if ("com.ptc.core.meta.container.common.impl.DiscreteSetConstraint".equals(cons.getRule().getRuleClassname())) {//合法值
				if (cons.getRuleDataObj() != null && cons.getRuleDataObj().getRuleData() instanceof DiscreteSet) {
					DiscreteSet dataSet = (DiscreteSet) cons.getRuleDataObj().getRuleData();
					Object[] els = dataSet.getElements();
					for (Object el : els) {
						avo.getLegalValueList().add(String.valueOf(el));
					}
				}else if(cons.getRule().getKey()!=null && 
						cons.getRule().getKey().contains("com.ptc.core.lwc.server.LWCEnumerationBasedConstraint") && 
						cons.getRuleDataObj()!=null){//枚举
					Collection<EnumerationEntryReadView> coll=cons.getRuleDataObj().getEnumDef().getAllEnumerationEntries().values();
					for(EnumerationEntryReadView eerv:coll){
						avo.getEnumMap().put(eerv.getName(),eerv.getPropertyValueByName(PROP_displayName).getValueAsString());
					}
				}
			} else if ("com.ptc.core.meta.container.common.impl.SingleValuedConstraint".equals(cons.getRule().getRuleClassname())) {//是否单值
				avo.setSingleValued(true);
			} else if ("com.ptc.core.meta.container.common.impl.ValueRequiredConstraint".equals(cons.getRule().getRuleClassname())) {//是否必须
				avo.setRequired(true);
			} else if ("com.ptc.core.meta.container.common.impl.StringLengthConstraint".equals(cons.getRule().getRuleClassname()) 
					|| "com.ptc.core.meta.container.common.impl.RangeConstraint".equals(cons.getRule().getRuleClassname())) {//有效范围
				if (cons.getRuleDataObj() != null
						&& cons.getRuleDataObj().getRuleData() instanceof com.ptc.core.meta.common.AnalogSet) {
					com.ptc.core.meta.common.AnalogSet aset = (com.ptc.core.meta.common.AnalogSet) cons.getRuleDataObj().getRuleData();
					if (aset.getRanges() != null) {
						Range range = aset.getRanges()[0];
						Integer length = ((Number) range.getUpperBoundValue()).intValue();
						avo.setLength(length);
					}
				}
			}else if (cons.getRule()!=null && LWCFilterBasedConstraint.class.getName().equals(cons.getRule().getDefClassname())) {//是否显示
				Object filter = cons.getFilter();
				if (filter !=null && filter instanceof ScreenDefinitionReadView) {
					ScreenDefinitionReadView sdr = (ScreenDefinitionReadView)filter;
					OperationIdentifier opId = sdr.getOperationId();
					PropertyValueReadView pvrv=cons.getRule().getPropertyValueByName(PROP_displayName);
					String v="3";
					if(pvrv!=null){
						String pvrVal=(String)pvrv.getValue();
                        if("Hidden".equalsIgnoreCase(pvrVal)){
                            v="0";
						}else if("Value Hidden".equalsIgnoreCase(pvrVal)){
							v="1";
						}else if("Immutable".equalsIgnoreCase(pvrVal)){
							v="2";
						}
					}
				}
			}

		}
	}
	
	/**
	 * 获取属性关联的全局内部名称
	 * @param typeName 类型名称，如：wt.part.WTPart
	 * @param attrName 属性名称，如：name
	 * @return
	 * @throws WTException
	 */
	public static String getAttrIBAInternalName(String typeName, String attrName) throws WTException {
		TypeDefinitionReadView tv = TypeDefinitionServiceHelper.service.getTypeDefView(typeName);
		AttributeDefinitionReadView av = tv.getAttributeByName(attrName);//得到属性视图
		String ibaInternalName = attrName;
		if(null != av) {
			String attrType = attrType(av);
			if(ATYPE_basic.equals(attrType)) {//标准属性
				ibaInternalName = av.getName();
			} else if(ATYPE_iba.equals(attrType)) {
				ibaInternalName = av.getIBARefView().getName();
			}
		}
		return ibaInternalName;
	}
	
	/**
	 * 获取属性关联的全局内部名称
	 * @param typeName 类型名称，如：wt.part.WTPart
	 * @param attrName 属性名称，如：name
	 * @return
	 * @throws WTException
	 */
	public static String getAttrDisplayName(String typeName, String attrName) throws WTException {
		TypeDefinitionReadView tv = TypeDefinitionServiceHelper.service.getTypeDefView(typeName);
		AttributeDefinitionReadView av = tv.getAttributeByName(attrName);//得到属性视图
		PropertyValueReadView propertyValueView = av.getPropertyValueByName(PROP_displayName);
		String displayName = String.valueOf(propertyValueView.getValue());
		return displayName;
	}
	
	/**
	 * 获取属性类型
	 * @param mv
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String attrType(AttributeDefinitionReadView mv) {
		String clsName = mv.getAttributeTypeIdentifier().getClass().getName();
		if (clsName.contains("NonPersistedAttributeTypeIdentifier")) {
			return ATYPE_ref;// folder.id 这种
		} else if (clsName.contains("ServerCalculatedAttributeTypeIdentifier")) {
			return ATYPE_mapping; // 安全标签，映射关系这种
		} else if (clsName.contains("ModeledAttributeTypeIdentifier")) {
			if (mv.getAttributeTypeIdentifier().getAttributeName().contains(".")) {
				return ATYPE_basic;// 扩列
			}
			return ATYPE_model; // 对象本身属性
		} else if (clsName.contains("InstanceBasedAttributeTypeIdentifier")) {
			return ATYPE_iba;
		}
		return null;
	}
}
